import Vue from 'vue'
import VueRouter from 'vue-router'
import {Message,Loading} from 'element-ui'
import jwt_decode from 'jwt-decode'

//防止当前连接与跳转连接重复报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {path: '/',redirect: '/admin',},
  {path:'/admin',
    name:'admin',
    component:() => import('../views/adminLayout'),
    children:[
      {path:'/',redirect: '/admin/index',},
      {path:'/admin/index',name:'adminIndex',component:() => import('../views/admin/index')},
      {path:'/admin/goods',name:'adminGoods',component:() => import('../views/admin/goods')},
      {path:'/admin/user',name:'adminUser',component:() => import('../views/admin/user')},
      {path:'/admin/order',name:'adminOrder',component:() => import('../views/admin/order')},
      {path:'/admin/set',name:'adminSet',component:() => import('../views/admin/setSlideImg')},
    ]
  },
  {path:'/common',
    name:'common',
    component:() => import('../views/commonLayout'),
    children:[
      {path:'/',redirect: '/common/index',},
      {path:'/common/index',name:'commonIndex',component:() => import('../views/common/index')},
      {path:'/common/category',name:'commonCategory',component:() => import('../views/common/category')},
      {path:'/common/detail',name:'commonDetail',component:() => import('../views/common/detail')},
      {path:'/common/cart',name:'commonCart',component:() => import('../views/common/cart')},
    ]
  },
  {path:'/login',name:'login',component:() => import('../views/login'),},
  {path:'/register',name:'register',component:() => import('../views/register'),},
  {path:'/*',name:'404',component:() => import('../views/notFound404'),}
]

const router = new VueRouter({
  routes,
  mode:'history'
})

//路由前置守卫
router.beforeEach((to, from, next) => {
  //登录和注册页面不论是否有token都可以正常访问
  if(to.path === '/login' || to.path === '/register'){
    next()
    return;
  }
  // 不存在token，就去登录
  if(!localStorage.getItem('tokenKey')){
    next('/login')
    return;
  }
  //判断token是否存在，存在则表示在登录状态下
  let user = jwt_decode(localStorage.getItem('tokenKey'))
  // admin可以进common,common不可以进admin
  // 如果是common后面的路由就放行，不是就跳转common首页
  if(user.identity === 'common'){
    if(to.path.slice(0,7) === '/common'){
      next()
      return;
    }else{
      next('/common')
      return;
    }
  }
  // 失败的方法(这里用一个研究了一个下午,后面还没对,又研究了两个小时)
  // if(user.identity === 'common' && to.path === '/common'){
  //   next('/common')
  //   return;
  // }

  next()
  
})

// 路由后置守卫
// router.afterEach((to, from) => {
// })

export default router
